<script lang="ts" setup name="MainHealthProblems">
import {reactive, ref, watch, onMounted, computed} from 'vue'
import {ElMessage, FormRules} from 'element-plus'
import useUser from '@/store/user'
import {
  getMainHealthProblems,
  saveMainHealthProblems,
  rejectMainHealthProblems,
  MainHealthProblems,
  MainHealthProblemsParams
} from '@/api/medicalExaminerDesk/beginPhysicalExamination/mainHealthProblems'
import {ChecksOrRadios, fieldRequired} from '@/api/medicalExaminerDesk/beginPhysicalExamination'
import {NotLeadingAndTrailingSpaces} from '@/util/common'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

// 主要健康问题表单
const healthProblemsForm = reactive<MainHealthProblems>({
  cereDiseCheckbox: ['1'], // 脑血管疾病勾选
  cereDise: '', // 脑血管疾病
  cereDiseOthers: '', // 脑血管疾病其他信息
  kidneyDiseCheckbox: ['1'], // 肾脏疾病勾选
  kidneyDise: '', // 肾脏疾病
  kidneyDiseOthers: '', // 肾脏疾病其他信息
  heartDiseCheckbox: ['1'], // 心脏疾病勾选
  heartDise: '', // 心脏疾病
  heartDiseOthers: '', // 心脏疾病其他信息
  vascuDiseCheckbox: ['1'], // 血管疾病勾选
  vascuDise: '', // 血管疾病
  vascuDiseOthers: '', // 血管疾病其他信息
  eyeDiseCheckbox: ['1'], // 眼部疾病勾选
  eyeDise: '', // 眼部疾病
  eyeDiseOthers: '', // 眼部疾病其他信息
  nervousDise: '1', // 神经系统疾病
  nervousDiseExist: '', // 神经系统疾病信息
  otherDise: '1', // 其他系统疾病 - 1、未发现 ，2、有
  otherDiseRedio: '1', // 其他系统疾病 - 1、未发现 ，2、有
  otherDiseExist: '' // 其他系统疾病信息
})

// 高血压勾选
const hypertension = ref(false)

// 糖尿病勾选
const diabetes = ref(false)

// 脑血管疾病
const cereDiseCheckboxs: Array<ChecksOrRadios> = [
  {label: '未发现', value: '1'},
  {label: '缺血性卒中', value: '2'},
  {label: '脑出血', value: '3'},
  {label: '蛛网膜下腔出血', value: '4'},
  {label: '短暂性脑缺血发作', value: '5'},
  {label: '其他', value: '6'}
]

// 肾脏疾病
const kidneyDiseCheckboxs: Array<ChecksOrRadios> = [
  {label: '未发现', value: '1'},
  {label: '糖尿病肾病', value: '2'},
  {label: '肾功能衰竭', value: '3'},
  {label: '急性肾炎', value: '4'},
  {label: '慢性肾炎', value: '5'},
  {label: '其他', value: '6'}
]

// 心脏疾病
const heartDiseCheckboxs: Array<ChecksOrRadios> = [
  {label: '未发现', value: '1'},
  {label: '心肌梗死', value: '2'},
  {label: '心绞痛', value: '3'},
  {label: '冠状动脉血运重建', value: '4'},
  {label: '充血性心力衰竭', value: '5'},
  {label: '心前区疼痛', value: '6'},
  {label: '其他', value: '7'}
]

// 血管疾病
const vascuDiseCheckboxs: Array<ChecksOrRadios> = [
  {label: '未发现', value: '1'},
  {label: '夹层动脉瘤', value: '2'},
  {label: '动脉闭塞性疾病', value: '3'},
  {label: '其他', value: '4'}
]
// 眼部疾病
const eyeDiseCheckboxs: Array<ChecksOrRadios> = [
  {label: '未发现', value: '1'},
  {label: '视网膜出血或渗出', value: '2'},
  {label: '视乳头水肿', value: '3'},
  {label: '白内障', value: '4'},
  {label: '其他', value: '5'}
]

// 表单实例
const formRef = ref()

// 体检大类的体检医生姓名
const dutyDoctorName5 = computed(() => {
  return healthProblemsForm.dutyDoctorName || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

// 体检状态
const checkupStatus5 = computed(() => {
  return healthProblemsForm.checkupStatus
})

// 校验
const rules = computed<FormRules>(() => {
  return {
    // 脑血管疾病
    cereDiseCheckbox: [{required: fieldRequired('cereDise'), message: '请选择脑血管疾病!', trigger: ['change', 'blur']}],
    // 肾脏疾病
    kidneyDiseCheckbox: [{required: fieldRequired('kidneyDise'), message: '请选择肾脏疾病!', trigger: ['change', 'blur']}],
    // 心脏疾病
    heartDiseCheckbox: [{required: fieldRequired('heartDise'), message: '请选择心脏疾病!', trigger: ['change', 'blur']}],
    // 血管疾病
    vascuDiseCheckbox: [{required: fieldRequired('vascuDise'), message: '请选择血管疾病!', trigger: ['change', 'blur']}],
    // 眼部疾病
    eyeDiseCheckbox: [{required: fieldRequired('eyeDise'), message: '请选择眼部疾病!', trigger: ['change', 'blur']}],
    // 脑血管疾病其他信息
    cereDiseOthers: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 肾脏疾病其他信息
    kidneyDiseOthers: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 心脏疾病其他信息
    heartDiseOthers: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 血管疾病其他信息
    vascuDiseOthers: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 眼部疾病其他信息
    eyeDiseOthers: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 神经系统疾病
    nervousDise: [{required: fieldRequired('nervousDise'), message: '请选择神经系统疾病!', trigger: ['change', 'blur']}],
    // 神经系统疾病信息
    nervousDiseExist: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ],
    // 其他系统疾病
    otherDiseRedio: [{required: fieldRequired('otherDise'), message: '请选择其他系统疾病!', trigger: ['change', 'blur']}],
    // 其他系统疾病信息
    otherDiseExist: [
      {pattern: NotLeadingAndTrailingSpaces, message: '首尾不能为空格！', trigger: ['change', 'blur']},
      {max: 100, message: '最多100个字符！', trigger: ['change', 'blur']}
    ]
  }
})

// 监听其他系统疾病输入框
watch(
  () => healthProblemsForm.otherDiseExist,
  (value) => {
    hypertension.value = value?.indexOf('高血压') !== -1
    diabetes.value = value?.indexOf('糖尿病') !== -1
  }
)

// 高血压勾选
const handleHypertensionChange = (value) => {
  healthProblemsForm.otherDiseExist = value ? healthProblemsForm.otherDiseExist?.concat(' ', '高血压').trim() : healthProblemsForm.otherDiseExist?.replace(/高血压/g, '')?.trim()
}

// 糖尿病勾选
const handleDiabetesChange = (value) => {
  healthProblemsForm.otherDiseExist = value ? healthProblemsForm.otherDiseExist?.concat(' ', '糖尿病').trim() : healthProblemsForm.otherDiseExist?.replace(/糖尿病/g, '')?.trim()
}

/**
 * @description: 获取体检信息
 * @return {*}
 */
const getInitData = () => {
  props.checkupRegisterId &&
    getMainHealthProblems(props.checkupRegisterId)
      .then((res) => {
        const {data} = res.data
        // 浅拷贝
        Object.assign(healthProblemsForm, data)
        healthProblemsForm.cereDiseCheckbox = data?.cereDise?.split('|') || ['1'] // 脑血管疾病复选
        healthProblemsForm.kidneyDiseCheckbox = data?.kidneyDise?.split('|') || ['1'] // 肾脏疾病复选
        healthProblemsForm.heartDiseCheckbox = data?.heartDise?.split('|') || ['1'] // 心脏疾病复选
        healthProblemsForm.vascuDiseCheckbox = data?.vascuDise?.split('|') || ['1'] // 血管疾病复选
        healthProblemsForm.eyeDiseCheckbox = data?.eyeDise?.split('|') || ['1'] // 眼部疾病复选
        healthProblemsForm.otherDiseExist = data?.otherDiseExist || ''
        healthProblemsForm.nervousDise = data?.nervousDise || '1'
        healthProblemsForm.otherDiseRedio =
          data?.otherDise?.split('|')?.filter((item) => {
            return item !== '' // 去掉空串脏数据
          })[0] || '1' // 饮食习惯单选
      })
      .finally(() => {
        showSaveLoading.value = false
      })
}

// 表单参数
const formDataParams = computed<MainHealthProblemsParams>(() => {
  return {
    cereDise: healthProblemsForm.cereDiseCheckbox?.join('|'), // 脑血管疾病
    cereDiseOthers: healthProblemsForm.cereDiseCheckbox?.indexOf('6') !== -1 ? healthProblemsForm.cereDiseOthers : null, // 脑血管疾病其他信息
    kidneyDise: healthProblemsForm.kidneyDiseCheckbox?.join('|'), // 肾脏疾病
    kidneyDiseOthers: healthProblemsForm.kidneyDiseCheckbox?.indexOf('6') !== -1 ? healthProblemsForm.kidneyDiseOthers : null, // 肾脏疾病其他信息
    heartDise: healthProblemsForm.heartDiseCheckbox?.join('|'), // 心脏疾病
    heartDiseOthers: healthProblemsForm.heartDiseCheckbox?.indexOf('7') !== -1 ? healthProblemsForm.heartDiseOthers : null, // 心脏疾病其他信息
    vascuDise: healthProblemsForm.vascuDiseCheckbox?.join('|'), // 血管疾病
    vascuDiseOthers: healthProblemsForm.vascuDiseCheckbox?.indexOf('4') !== -1 ? healthProblemsForm.vascuDiseOthers : null, // 血管疾病其他信息
    eyeDise: healthProblemsForm.eyeDiseCheckbox?.join('|'), // 眼部疾病
    eyeDiseOthers: healthProblemsForm.eyeDiseCheckbox?.indexOf('5') !== -1 ? healthProblemsForm.eyeDiseOthers : null, // 眼部疾病其他信息
    nervousDise: healthProblemsForm.nervousDise, // 神经系统疾病
    nervousDiseExist: healthProblemsForm.nervousDise === '2' ? healthProblemsForm.nervousDiseExist : null, // 神经系统疾病信息
    otherDise: healthProblemsForm.otherDiseRedio === '2' ? healthProblemsForm.otherDiseRedio + `${hypertension.value ? `${'|' + 3}` : ''}` + `${diabetes.value ? `${'|' + 4}` : ''}` : '1', // 其他系统疾病 - 1、未发现 ，2、有 3高血压 4糖尿病
    otherDiseExist: healthProblemsForm.otherDiseRedio === '2' ? healthProblemsForm.otherDiseExist : '' // 其他系统疾病信息
  }
})

/**
 * @description: 保存
 * @return {*}
 */
const onSave5 = () => {
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        const params = {
          ...formDataParams.value,
          checkupStatus: 2, // 已检
          id: healthProblemsForm.id, // 表单Id
          checkupRegisterId: props.checkupRegisterId, // 体检登记表id
          dutyDoctorId: healthProblemsForm.dutyDoctorId || user.userInfor?.id, // 体检医生id
          dutyDoctorName: healthProblemsForm.dutyDoctorId !== user.userInfor?.id ? healthProblemsForm.dutyDoctorName || user.userInfor?.userName : user.userInfor?.userName // 体检医生姓名
        }
        saveMainHealthProblems(params)
          .then(() => {
            getInitData()
            ElMessage.success('保存成功!')
          })
          .catch((err) => {
            showSaveLoading.value = false
            console.warn(err)
          })
      } else {
        console.log(fields)
      }
    })
}

/**
 * @description: 拒检
 * @return {*}
 */
const onRejectInspection5 = () => {
  showMessageBox('是否对该体检大类进行拒检操作？', {title: '拒检确认', mesageType: 'base'})
    .then(() => {
      showSaveLoading.value = true
      const nullParams: MainHealthProblemsParams = {...formDataParams.value}
      // 置空
      Object.keys(formDataParams.value)?.forEach((item) => {
        nullParams[item] = null
      })
      const params = {
        ...nullParams,
        checkupStatus: 1, // 1拒检
        id: healthProblemsForm.id, // 表单Id
        checkupRegisterId: props.checkupRegisterId, // 体检登记表id
        dutyDoctorId: healthProblemsForm.dutyDoctorId || user.userInfor?.id, // 体检医生id
        dutyDoctorName: healthProblemsForm.dutyDoctorId !== user.userInfor?.id ? healthProblemsForm.dutyDoctorName || user.userInfor?.userName : user.userInfor?.userName // 体检医生姓名
      }
      rejectMainHealthProblems(params)
        .then(() => {
          ElMessage.success('拒检成功!')
          getInitData()
        })
        .catch((error) => {
          showSaveLoading.value = false
          console.warn(error)
        })
    })
    .catch((error) => {
      console.warn(error)
    })
}

/**
 * @description: 勾选框互斥判断
 * @param {*} key 键，用来改变对应复选框的值
 * @param {*} value 值 '1'是未发现异常
 * @return {*}
 */
const onChangeCheckboxs = (key: string, value: string) => {
  if (value === '1') {
    healthProblemsForm[key].length ? (healthProblemsForm[key] = ['1']) : (healthProblemsForm[key] = [])
  } else {
    healthProblemsForm[key] = healthProblemsForm[key].filter((item) => {
      return item !== '1'
    })
  }
}

onMounted(() => {
  getInitData()
})
</script>
<template>
  <el-form ref="formRef" class="d-check-up-desk-content" label-position="top" :model="healthProblemsForm" :rules="rules" :disabled="disEdit">
    <el-form-item label="脑血管疾病" prop="cereDiseCheckbox" class="health-problems-form-item">
      <el-checkbox-group v-model="healthProblemsForm.cereDiseCheckbox">
        <el-checkbox v-for="item in cereDiseCheckboxs" :key="item.value" :label="item.value" @change="onChangeCheckboxs('cereDiseCheckbox', item.value + '')">
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-form-item v-show="healthProblemsForm.cereDiseCheckbox.indexOf('6') !== -1" prop="cereDiseOthers" class="others">
        <el-input v-model="healthProblemsForm.cereDiseOthers" clearable />
      </el-form-item>
    </el-form-item>
    <el-form-item label="肾脏疾病" prop="kidneyDiseCheckbox" class="health-problems-form-item">
      <el-checkbox-group v-model="healthProblemsForm.kidneyDiseCheckbox">
        <el-checkbox v-for="item in kidneyDiseCheckboxs" :key="item.value" :label="item.value" @change="onChangeCheckboxs('kidneyDiseCheckbox', item.value + '')">
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-form-item v-show="healthProblemsForm.kidneyDiseCheckbox.indexOf('6') !== -1" prop="kidneyDiseOthers" class="others">
        <el-input v-model="healthProblemsForm.kidneyDiseOthers" clearable />
      </el-form-item>
    </el-form-item>
    <el-form-item label="心脏疾病" prop="heartDiseCheckbox" class="health-problems-form-item">
      <el-checkbox-group v-model="healthProblemsForm.heartDiseCheckbox">
        <el-checkbox v-for="item in heartDiseCheckboxs" :key="item.value" :label="item.value" @change="onChangeCheckboxs('heartDiseCheckbox', item.value + '')">
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-form-item v-show="healthProblemsForm.heartDiseCheckbox.indexOf('7') !== -1" prop="heartDiseOthers" class="others">
        <el-input v-model="healthProblemsForm.heartDiseOthers" clearable />
      </el-form-item>
    </el-form-item>
    <el-form-item label="血管疾病" prop="vascuDiseCheckbox" class="health-problems-form-item">
      <el-checkbox-group v-model="healthProblemsForm.vascuDiseCheckbox">
        <el-checkbox v-for="item in vascuDiseCheckboxs" :key="item.value" :label="item.value" @change="onChangeCheckboxs('vascuDiseCheckbox', item.value + '')">
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-form-item v-show="healthProblemsForm.vascuDiseCheckbox.indexOf('4') !== -1" prop="vascuDiseOthers" class="others">
        <el-input v-model="healthProblemsForm.vascuDiseOthers" clearable />
      </el-form-item>
    </el-form-item>
    <el-form-item label="眼部疾病" prop="eyeDiseCheckbox" class="health-problems-form-item">
      <el-checkbox-group v-model="healthProblemsForm.eyeDiseCheckbox">
        <el-checkbox v-for="item in eyeDiseCheckboxs" :key="item.value" :label="item.value" @change="onChangeCheckboxs('eyeDiseCheckbox', item.value + '')">
          {{ item.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-form-item v-show="healthProblemsForm.eyeDiseCheckbox.indexOf('5') !== -1" prop="eyeDiseOthers" class="others">
        <el-input v-model="healthProblemsForm.eyeDiseOthers" clearable />
      </el-form-item>
    </el-form-item>
    <el-form-item label="神经系统疾病" prop="nervousDise" class="health-problems-form-item">
      <el-radio-group v-model="healthProblemsForm.nervousDise">
        <el-radio label="1">
          未发现
        </el-radio>
        <el-radio label="2">
          有
        </el-radio>
      </el-radio-group>
      <el-form-item v-show="healthProblemsForm.nervousDise === '2'" prop="nervousDiseExist" class="others">
        <el-input v-model="healthProblemsForm.nervousDiseExist" clearable />
      </el-form-item>
    </el-form-item>
    <el-form-item label="其他系统疾病" prop="otherDiseRedio" class="health-problems-form-item other-dise">
      <el-radio-group v-model="healthProblemsForm.otherDiseRedio">
        <el-radio label="1">
          未发现
        </el-radio>
        <el-radio label="2">
          有
        </el-radio>
      </el-radio-group>
      <el-form-item v-show="healthProblemsForm.otherDiseRedio === '2'">
        <el-checkbox v-model="hypertension" label="高血压" @change="handleHypertensionChange" />
        <el-checkbox v-model="diabetes" label="糖尿病" @change="handleDiabetesChange" />
        <el-form-item prop="otherDiseExist" class="others">
          <el-input v-model="healthProblemsForm.otherDiseExist" clearable />
        </el-form-item>
      </el-form-item>
    </el-form-item>
  </el-form>
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName5" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onSave5()">
      保存
    </el-button>
    <el-button type="danger" :loading="showSaveLoading" :disabled="(checkupStatus5 && checkupStatus5 === 1) || disEdit" plain @click="onRejectInspection5()">
      拒检
    </el-button>
  </div>
</template>
<style lang="less" scoped>
.health-problems-form-item {
  padding-bottom: 18px;
  margin-bottom: 18px;
  border-bottom: 1px solid rgba(195, 201, 210, 1);
  &:last-child {
    border-bottom: none;
  }
  :deep(.el-form-item__label) {
    color: var(--d-font-color-text);
    font-weight: bold;
    display: inline-flex;
    align-items: center;
  }
  :deep(.el-form-item__content) {
    margin-left: 20px;
  }
  .el-input {
    margin-left: 20px;
    height: 32px;
    width: 300px;
  }
}

.others {
  :deep(.el-form-item__content) {
    margin-left: 0;
  }
}
</style>
